<template>
  <div class="dashboard-container">
    <div class="app-container">
      <my-header :show-before="true">
        <span slot="before">共{{ total }}条记录</span>
        <template slot="after">
          <el-button size="small" type="warning" @click="$router.push('/import')">导入</el-button>
          <el-button size="small" type="danger" @click="exportFn">导出</el-button>
          <el-button size="small" type="primary" @click="showDialog=true">新增员工</el-button>
        </template>
      </my-header>
      <!-- 放置表格和分页 -->
      <el-card>
        <el-table v-loading="loading" border :data="list">
          <el-table-column label="序号" width="120">
            <template #default="{$index}">
              {{ ( pager.page - 1 ) * pager.size + ( $index + 1 ) }}
            </template>
          </el-table-column>
          <el-table-column label="头像" sortable="" prop="staffPhoto" width="80">
            <template #default="{row}">
              <img
                v-imgErr="require('@/assets/common/02.jpg')"
                :src="row.staffPhoto"
                alt=""
                class="avator"
                @click="showQRCode(row.staffPhoto)"
              >
            </template>
          </el-table-column>
          <el-table-column label="姓名" sortable="" prop="username" />
          <el-table-column label="工号" sortable="" prop="workNumber" />
          <el-table-column :formatter="formatterFormOfEmployment" label="聘用形式" sortable="" prop="formOfEmployment" />
          <el-table-column label="部门" sortable="" prop="departmentName" />
          <el-table-column label="入职时间" sortable="">
            <template #default="{row}">
              {{ row.timeOfEntry | formatDate }}
            </template>
          </el-table-column>
          <el-table-column label="账户状态" sortable="">
            <template #default="{row}">
              <el-switch
                :value="row.enableState === 1"
              />
            </template>
          </el-table-column>
          <el-table-column label="操作" sortable="" fixed="right" width="280">
            <template #default="{row}">
              <el-button type="text" size="small" @click="$router.push(`/employees/detail/${row.id}`)">查看</el-button>
              <el-button type="text" size="small" :disabled="!checkIsPermission('1')">转正</el-button>
              <el-button type="text" size="small">调岗</el-button>
              <el-button type="text" size="small">离职</el-button>
              <el-button type="text" size="small" @click="assignRole(row.id)">角色</el-button>
              <el-button type="text" size="small" @click="del(row.id)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
        <!-- 分页组件 -->
        <el-row type="flex" justify="center" align="middle" style="height: 60px">
          <el-pagination
            :current-page="pager.page"
            :page-sizes="[5, 10, 15, 20]"
            :page-size="pager.size"
            layout="total, sizes, prev, pager, next, jumper"
            :total="total"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
          />
        </el-row>
      </el-card>
      <add-employee :show-dialog="showDialog" />
      <assign-role ref="assignRole" :is-show="showRole" :user-id="userId" @btnCancel="btnCancel2" />
      <el-dialog title="二维码" :visible="showCode" @close="btnCancel">
        <el-row type="flex" justify="center">
          <!-- 二维码 -->
          <canvas ref="myCanvas" />
        </el-row>
      </el-dialog>
    </div>
  </div>
</template>

<script>
import myHeader from '@/components/myHeader.vue'
import { getEmployeeList, delEmployee } from '@/api/employee'
import EnmaEmployees from '@/api/constant/employees'
import { formatDate } from '@/filters'
import addEmployee from './addEmployee.vue'
import QRCode from 'qrcode'
import AssignRole from './assignRole.vue'
export default {
  components: {
    myHeader,
    addEmployee,
    AssignRole
  },
  data() {
    return {
      // 分页
      pager: {
        page: 1,
        size: 5
      },
      // 总条数
      total: 0,
      // 获取的员工列表
      list: [],
      loading: false,
      // 显示新增员工弹框
      showDialog: false,
      showCode: false,
      showRole: false,
      userId: ''
    }
  },
  mounted() {
    // 发请求获取员工列表
    this.getList()
  },
  methods: {
    // 封装获取员工列表
    async getList() {
      this.loading = true
      const { rows, total } = await getEmployeeList(this.pager)
      this.total = total
      this.list = rows
      this.loading = false
    },
    // 分页 -- 切换页码
    handleCurrentChange(val) {
      this.pager.page = val
      this.getList()
    },
    // 分页 -- 切换显示容量
    handleSizeChange(val) {
      this.pager.size = val
      this.getList()
    },
    // 聘用形式数据处理---枚举数据+列格式化属性
    formatterFormOfEmployment(row, col, cellValue, index) {
      const obj = EnmaEmployees.hireType.find(item => item.id === Number(cellValue))
      return obj ? obj.value : '不确定'
    },
    // 导出按钮
    async exportFn() {
      // 导入插件
      const { export_json_to_excel } = await import('@/vendor/Export2Excel')
      // 获取全部员工数据
      const { rows } = await getEmployeeList({ page: 1, size: this.total })
      // 定义字典
      const dict = {
        '手机号': 'mobile',
        '姓名': 'username',
        '入职日期': 'timeOfEntry',
        '聘用形式': 'formOfEmployment',
        '转正日期': 'correctionTime',
        '工号': 'workNumber',
        '部门': 'departmentName'
      }
      // 生成表头
      const header = Object.keys(dict)
      // 生成表格主体
      const data = rows.map(user => {
        return this.obj2arr(user, dict)
      })
      export_json_to_excel({
        header,
        data
      })
    },
    // 对象转数组
    obj2arr(user, dict) {
      const newArr = []
      for (const key in dict) {
        const enkey = dict[key]
        let value = user[enkey]
        // 处理时间
        if (enkey === 'timeOfEntry' || enkey === 'correctionTime') {
          value = formatDate(value)
        }
        // 处理聘用形式
        if (enkey === 'formOfEmployment') {
          const obj = EnmaEmployees.hireType.find(item => item.id === value)
          value = obj ? obj.value : '不确定'
        }
        newArr.push(value)
      }
      return newArr
    },
    // 删除
    async del(id) {
      try {
        // 询问
        await this.$confirm('您确定删除该员工吗?', '温馨提示', {

          type: 'warning'
        })
        // 发请求
        await delEmployee(id)
        // 最后一条
        if (this.list.length === 1 && this.pager.page > 1) {
          this.pager.page--
        }
        // 提醒
        this.$message.success('删除成功')
        // 更新页面
        this.getList()
      } catch (error) {
        console.log(error)
      }
    },
    // 二维码
    showQRCode(url) {
      console.log(url)
      if (url) {
        this.showCode = true
        this.$nextTick(() => {
          QRCode.toCanvas(this.$refs.myCanvas, url, {
            color: {
              dark: '#4676fa'
            }
          })
        })
      }
    },
    // 弹框取消
    btnCancel() {
      this.showCode = false
    },
    // 弹框取消
    btnCancel2() {
      this.showRole = false
    },
    // 角色按钮
    assignRole(id) {
      this.userId = id
      this.$refs.assignRole.getRoleDetailById(id)
      this.showRole = true
    }
  }
}
</script>

<style lang="scss" scoped>
.avator {
  width: 90%;
  height: 50px;
  object-fit: contain;
}
</style>
